<%--
  Created by IntelliJ IDEA.
  User: Lanan
  Date: 2017/12/20 0020
  Time: 17:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/commons/global.jsp" %>
<html>
<head>
    <%@ include file="/commons/basejs.jsp" %>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>文章管理</title>
</head>
<body>
<div class="easyui-layout" fit="true" >
    <div data-options="region:'west',split:true,border:false" title="文章分类列表" style="width:30%;">
        <table id="article_categary_grid" class="easyui-treegrid"
               data-options="
		   		url:'${path}/article/category/list.do',
		   		fit:true,
		   		idField:'id',
		   		treeField:'name',
		   		parentField : 'parentId',
		   		fitColumns: true,
		   		toolbar:'#tools',
		   		pagination:false,
		   		singleSelect:true,
		   		onClickRow:function(row){
		   		    getArticleApply(row.id, row.level);
		   		},">
            <thead>
            <th data-options="field:'name', align:'left'">分类名称</th>
            <th data-options="field:'logo', align:'center', formatter:formatterImg">分类logo</th>
            <th data-options="field:'status',align:'center',formatter:formatterStatus">是否启用</th>
            <th data-options="field:'ord',align:'center'">排序</th>
            </thead>
        </table>
        <div id="tools">
            <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-reload'" onclick="$('#article_categary_grid').treegrid('reload');">刷新</a>
            <shiro:hasPermission name="/article/category/insert.do">
                <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-add'" onclick="insertArticleCategory()">添加</a>
            </shiro:hasPermission>
            <shiro:hasPermission name="/article/category/update.do">
                <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-edit'" onclick="updateArticleCategory()">修改</a>
            </shiro:hasPermission>
            <shiro:hasPermission name="/article/category/delete.do">
                <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-remove'" onclick="deleteArticleCategory()">删除</a>
            </shiro:hasPermission>
            <shiro:hasPermission name="/article/changeArticleStatusToEnableOrDisable.do">
                <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-tip'" onclick="changeCategoryAble()">启用|禁用</a>
            </shiro:hasPermission>

        </div>
    </div>
    <%--编辑与添加分类--%>
    <div class="easyui-dialog" id="article_categary_edit_dialog" data-options="closed:true,modal:true,width:500,height:350">
        <form id="article_categary_edit_form" method="post">
            <table align="center" width="100%" style="margin-top: 20px" cellpadding="4">
                <input type="hidden" name="id"/>
                <input type="hidden" name="status">
                <tr>
                    <td align="right" width="30%"><lable for="name">文章分类名称:</lable></td>
                    <td width="70%">
                        <input id="edit_name" name="name" class="easyui-validatebox" data-options="required:true,missingMessage:'请输入文章分类名称'"/>
                    </td>
                    <td></td>
                </tr>
                <tr>
                    <td align="right" width="30%"><lable for="name">分类logo:</lable></td>
                    <td>
                        <div id="upload_ue"></div>
                        <div>
                            <%-- style="border: 1px solid lightgrey"--%>
                            <img id="logoUrl" align="center" height="90" width="90">
                            <input type="hidden" id="picture" name="logo" data-options="required:true"/>
                            <input style="margin-left: 10px" type="button" onclick="upImage();" value="上传图片">
                        </div>
                    </td>
                </tr>
                <tr>
                    <td align="right" width="30%"><lable for="parentId">上级分类:</lable></td>
                    <td width="70%">
                        <select id="edit_category_parent" name="parentId" style="width:140px;"></select>
                        <a class="easyui-linkbutton" href="javascript:void(0)" onclick="$('#edit_category_parent').combotree('clear');$('#edit_category_parent').combotree('setValue', '');" >清空</a>
                    </td>
                </tr>
                <tr>
                    <td align="right" width="30%"><lable for="ord">排序:</lable></td>
                    <td width="70%">
                        <input name="ord" id="articleCategoryOrd" value="0" class="easyui-numberspinner" style="width: 140px;" required="required" data-options="required:false,editable:true,missingMessage:'请输入排序序号（大前小后）'">
                    </td>
                </tr>
            </table>
            <div style="margin-top: 20px;text-align: center">
                <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-save'", onclick="uploadOrInsertHandel()">提交</a>
                <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'", onclick="$('#article_categary_edit_dialog').dialog('close')">取消</a>
            </div>
        </form>
    </div>

    <script type="text/javascript">

        var _editor;
        $(function() {
            //重新实例化一个编辑器，防止在上面的editor编辑器中显示上传的图片或者文件
            _editor = UE.getEditor('upload_ue',{
                serverUrl:"${path}/file/upload.do?compress=1"
            });

            _editor.ready(function () {
                //设置编辑器不可用
                // _editor.setDisabled();
                //隐藏编辑器，因为不会用到这个编辑器实例，所以要隐藏
                _editor.hide();
                //侦听图片上传
                _editor.addListener('beforeInsertImage', function (t, arg) {
                    //有多少张图片arg.length就是多大
                    $("#picture").val(arg[0].src);
                    $("#logoUrl").attr('src',arg[0].src);
                });
            });
        });

        //弹出图片上传的对话框
        function upImage() {
            var myImage = _editor.getDialog("insertimage");
            myImage.open();
        }

        function changeCategoryAble() {
            var select = $("#article_categary_grid").treegrid("getSelected");
            if (select == null) {
                $.messager.alert("提示","请选择要操作的文章分类！","info");
                return;
            }
            changeArticleStatusToEnableOrDisable(true, select.id, select.status);
        }

        // 启用与禁用
        function changeArticleStatusToEnableOrDisable(isCategory, id, status1) {
            var msg = "";
            var status;
            var url = "";
            if (status1 == 0) {
                msg = "启用";
                status = 1;
            } else {
                msg = "禁用";
                status = 0;
            }
            if (isCategory) {
                msg += "该文章分类";
                if (status == 0) msg += ", 禁用该分类, 该下的所有子分类和文章将被禁用! ";
                url = "${path}/article/category/changeCategoryStatusToEnableOrDisable.do";
            } else {
                msg += "所选文章";
                if (status == 1) {
                    msg += ", 注意: 如果所选文章所属分类未启用, 将无法启用该文章!";
                }
                url = "${path}/article/changeArticleStatusToEnableOrDisable.do";
            }
            $.messager.confirm("确认", "你确定要" + msg , function(yes){
                if(yes){
                    $.messager.progress();
                    $.ajax({
                        url:url,
                        type:"post",
                        data:{id:id, status:status},
                        dataType:"json",
                        success:function(data){
                            $.messager.progress("close");
                            if(data.success){
                                $.messager.show({
                                    title:"操作成功",
                                    msg:"操作成功!",
                                    timeout:600,
                                    style:"left:30%;top:10%",
                                    showType:"fade"
                                });
                                if (isCategory) {
                                    $("#article_categary_grid").treegrid("reload");
                                    $("#article_grid").datagrid("reload");
                                } else {
                                    $("#article_grid").datagrid("reload");
                                }
                            }else{
                                $.messager.alert("操作失败", data.msg,"error");
                            }
                        },
                        error:function(){
                            $.messager.progress("close");
                            $.messager.alert("操作失败", "服务器连接失败!","error");
                        }
                    });
                }
            });
        }


        function insertArticleCategory() {
            flag = 'add';
            $("#article_categary_edit_form").form("clear");
            handelCategoryCombobox("edit_category_parent");
            $("#logoUrl").attr("src", "");
            $("#article_categary_edit_dialog").dialog({title: "添加文章分类"});
            $("#article_categary_edit_dialog").dialog("open");
        }

        function updateArticleCategory() {
            flag = 'update';
            var select = $("#article_categary_grid").treegrid("getSelected");
            if(select == null){
                $.messager.alert("提示","请选择要修改的文章分类！","info");
                return;
            }
            handelCategoryCombobox("edit_category_parent");
            $("#article_categary_edit_form").form("load", select);
            if (select.parentId == null) {
                $("#edit_category_parent").combotree("clear");
            }
            $("#logoUrl").attr("src",select.logo);
            $('#article_categary_edit_dialog').dialog({title: "修改文章分类"});
            $("#article_categary_edit_dialog").dialog("open");
        }

        function handelCategoryCombobox(treeId) {
            $("#" + treeId).combotree({
                url : "${path}/article/category/getArticleCategoryCombobox.do",
                idField:'id',
                parentField : 'pid',
                lines : true,
                panelHeight : 'auto',
                editable:false,
                onLoadSuccess:function (data) {

                }
            });
        }

        function uploadOrInsertHandel() {
            var logo = $("#picture").val();
            if (logo == null || logo.length <= 0 || logo == "") {
                $.messager.show({
                    title:"提示",
                    msg: "请上传分类logo！",
                    timeout:1000,style:"left:30%;top:10%",
                    showType:"fade"
                });
                return;
            }
            var url = "";
            var msg = "";
            if (flag == "add") {
                url = "${path}/article/category/insert.do";
                msg = "添加";
            } else if (flag == "update") {
                url = "${path}/article/category/update.do";
                msg = "修改";
            }
            lananUpdateOrInsertTree(msg, url, "article_categary_edit_form", "article_categary_edit_dialog", "article_categary_grid");
        }

        function deleteArticleCategory() {
            var url = "${path}/article/category/delete.do";
            lananDeleteTree("article_categary_grid", "您确定要删除该文章分类?", url);
        }

    </script>


    <%--文章 --%>
    <div data-options="region:'center',split:true,border:false" title="文章列表" style="width:70%;">
        <table id="article_grid" class="easyui-datagrid"
               data-options="
		   		url:'${path}/article/list.do',
		   		fit:true,
		   		idField:'id',
		   		fitColumns: true,
		   		rownumbers:true,
		   		toolbar:'#article_tools',
		   		pagination:true,
		   		frozenColumns:[[
                {field:'ck',checkbox:true}]],
		   		singleSelect:false,
		   		width:$(this).width() * 0.1,
		   		">
            <thead>
            <%--<th data-options="field:'id', align:'center', checkbox:true">ID</th>--%>
            <th data-options="field:'title', align:'center'">文章名</th>
            <th data-options="field:'writer', align:'center'">作者</th>
            <th data-options="field:'source', align:'center'">来源</th>
            <th data-options="field:'thumbnailImg', align:'center', formatter:formatterImg">图片</th>
            <th data-options="field:'catagoryOne', align:'center'">一级分类</th>
            <th data-options="field:'catagoryTwo', align:'center'">二级分类</th>
            <th data-options="field:'openNum', align:'center'">阅读数</th>
            <th data-options="field:'intro',width:'50px', align:'center'">简介</th>
            <%--<th data-options="field:'content', align:'center'">内容</th>--%>
            <th data-options="field:'status',align:'center',formatter:formatterStatus">是否启用</th>
            <th data-options="field:'createTime',align:'center',formatter:formatDatebox">创建时间</th>
            <th data-options="field:'updateTime',align:'center',formatter:formatDatebox">更新时间</th>
            <th data-options="field:'ord',align:'center'">排序</th>
            </thead>
        </table>
        <div id="article_tools">
            <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-reload'" onclick="$('#article_grid').datagrid('reload');">刷新</a>
            <shiro:hasPermission name="/article/insert.do">
                <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-add'" onclick="insertArticle()">添加</a>
            </shiro:hasPermission>
            <shiro:hasPermission name="/article/update.do">
                <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-edit'" onclick="updateArticle()">修改</a>
            </shiro:hasPermission>
            <shiro:hasPermission name="/article/delete.do">
                <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-remove'" onclick="deleteArticle()">删除</a>
            </shiro:hasPermission>
            <shiro:hasPermission name="/article/category/changeCategoryStatusToEnableOrDisable.do">
                <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-tip'" onclick="changeArticleAble()">启用|禁用</a>
            </shiro:hasPermission>

            <form action="#" id="searchArticleForm">
                <label>标题:</label>
                <input class="easyui-textbox" id="search_article_title" name="articleTitle" data-options="prompt:'请输入搜索文章标题'"/>
                <label>作者:</label>
                <input class="easyui-textbox" id="search_article_author" name="articleAuthor" data-options="prompt:'请输入搜索文章作者'"/>
                <label>来源:</label>
                <input class="easyui-textbox" id="search_article_from" name="articleFrom" data-options="prompt:'请输入搜索文章来源'"/>
                <label>简介:</label>
                <input class="easyui-textbox" id="search_article_intro" name="articleIntro" data-options="prompt:'请输入搜索文章简介'"/>
                <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'" onclick="searchArticle()">搜索</a>
                <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-clear'" onclick="searchArticleReset()">重置</a>
            </form>
        </div>
    </div>

    <div id="editArticleEnableOrDisable" class="easyui-dialog"></div>

    <script type="text/javascript">

        var dlg = null;
        $(function () {
            dlg = $('#editArticleEnableOrDisable').dialog({
                title : "启用文章|禁用文章",
                buttons : [ {
                    id : "flagBttOne",
                    text : "启用",
                    handler : function() {
                        articleStatusToEnable();
                    }
                }, {
                    id : "flagBttTwo",
                    text : "禁用",
                    handler : function() {
                        articleStatusToDisable();
                    }
                }, {
                    text : "关闭",
                    handler : function() {
                        dlg.dialog('close');
                    }
                } ]
            });
            dlg.dialog('close');
        })

        function changeArticleAble() {
            var rowsData = $("#article_grid").datagrid("getSelections");//找到所有选中的行
            if (rowsData.length <= 0) {
                $.messager.alert("提示","请选择要操作的文章！","info");
                return;
            }
            dlg.dialog('open'); // 打开窗口

        }

        function articleStatusToEnable() {
            hanlelStatus(0)
        }

        function articleStatusToDisable() {
            hanlelStatus(1)
        }

        function hanlelStatus(status) {
            dlg.dialog('close');
            var rowsData = $("#article_grid").datagrid("getSelections");//找到所有选中的行
            var ids = "";
            if (rowsData.length > 0) {
                for (var i = 0; i < rowsData.length; i++) {
                    var row = rowsData[i];
                    if (i == rowsData.length - 1) ids += row.id;
                    else ids += row.id + ',';
                }
            }

            if (ids.length <= 0) {
                $.messager.alert("提示","请选择要操作的文章！","info");
                return;
            }
            changeArticleStatusToEnableOrDisable(false, ids, status);
        }

        // 文章搜索
        function searchArticle() {
            var queryParams = {};
            queryParams.articleTitle = $("#search_article_title").val();
            queryParams.articleAuthor = $("#search_article_author").val();
            queryParams.articleFrom = $("#search_article_from").val();
            queryParams.articleIntro = $("#search_article_intro").val();
            $("#article_grid").datagrid('options').queryParams = queryParams;
            $("#article_grid").datagrid('getPager').data("pagination").options.pageNumber = 1;
            var select = $('#article_grid').datagrid('getSelected');
            if(select != null){
                $('#article_grid').datagrid('clearSelections');
            }
            $("#article_grid").datagrid('reload');
        }

        // 搜索重置
        function searchArticleReset() {
            $("#searchArticleForm").form('clear');
        }

        function insertArticle() {
            $.modalDialog({
                title : '添加文章',
                id:'article_insert_dialog',
                width : 1000,
                height : 600,
                href : '${path }/article/insert/index.do',
            });
        }

        function updateArticle() {
            var rowsData = $("#article_grid").datagrid("getSelections");//找到所有选中的行
            if(rowsData.length > 1){
                $.messager.alert("提示","只能修改一项","info");
                return;
            }
            var select = $('#article_grid').datagrid('getSelected');
            if (select == null) {
                $.messager.alert("提示","请选择要修改的文章！","info");
                return;
            }
            $.modalDialog({
                title : '修改',
                id:'article_update_dialog',
                width : 1000,
                height : 600,
                href : '${path }/article/update/index.do?id=' + select.id,
            });
        }

        function deleteArticle() {
            var rowsData = $("#article_grid").datagrid("getSelections");//找到所有选中的行
            if(rowsData.length > 1){
                $.messager.alert("提示","只能删除一项","info");
                return;
            }
            var url = "/article/delete.do";
            lananDelete("article_grid", "确定删除该文章?", url);
        }
    </script>
</div>
<script type="text/javascript">
    function formatterImg(value){
        if(value!=null){
            return '<img height="30px" align="center" src="'+value+'" alt="" />';
        }else{
            return '';
        }
    }

    function formatterStatus(status) {
        if (status == 0) return '<span style="color:red">' + '禁用' + '</span>';
        else if (status == 1) return '<span style="color:green">' + '启用' + '</span>';
    }

    function getArticleApply(catagoryId, level) {
        var select = $("#article_grid").datagrid("getSelected");
        if(select != null){
            $('#article_grid').datagrid('clearSelections');
        }
        var queryParams = {};
        queryParams.catagoryId = catagoryId;
        queryParams.level = level;
        var options = $("#article_grid").datagrid('getPager').data("pagination").options;
        options.pageNumber = 1;
        //重新加载
        $("#article_grid").datagrid('options').queryParams = queryParams;
        $("#article_grid").datagrid('reload');
    }


    function lananUpdateOrInsertTree(msg, url, formId, closeId, reloadId) {
        $.messager.progress();
        $("#" + formId).form("submit",{
            url:url,
            onSubmit:function(){
                var valid = $(this).form("validate");
                if (!valid) {
                    $.messager.progress("close");
                }
                return valid;
            },
            success:function(data){
                data=$.parseJSON(data);
                $.messager.progress("close");
                if(data.success){
                    $("#" + closeId).dialog("close");
                    $.messager.show({
                        title: msg + "成功",msg: msg + "成功!",
                        timeout:600,style:"left:30%;top:10%",
                        showType:"fade"
                    });
                    $("#" + reloadId).treegrid("reload");
                    $('#' + reloadId).treegrid('clearSelections');
                    if (flag == "update") {
                        $("#article_grid").datagrid('clearSelections');
                        $("#article_grid").datagrid("reload");
                    }
                }else{
                    $.messager.alert(msg + "失败", data.msg,"error");
                }
            },
            error:function () {
                $.messager.progress("close");
                $.messager.alert("操作失败", "服务器连接失败!","error");
            }
        });
    }
    function lananDeleteTree(lableId, alertStr, url) {
        var select = $('#' + lableId).datagrid('getSelected');
        if (select == null) {
            $.messager.alert("提示","请选择要删除的项！","info");
            return;
        }
        $.messager.confirm("确认",alertStr, function(yes){
            if(yes){
                $.messager.progress();
                $.ajax({
                    url:url,
                    type:"post",
                    data:{id : select.id, openid : select.openid},
                    dataType:"json",
                    success:function(data){
                        $.messager.progress("close");
                        if(data.success){
                            $.messager.show({
                                title:"删除成功",
                                msg:"删除成功!",
                                timeout:600,
                                style:"left:30%;top:10%",
                                showType:"fade"
                            });
                            $("#" + lableId).treegrid('clearSelections');
                            $("#" + lableId).treegrid("reload");
                        }else{
                            $.messager.alert("删除失败", data.msg,"error");
                        }
                    },
                    error:function(){
                        $.messager.progress("close");
                        $.messager.alert("删除失败", "服务器连接失败!","error");
                    }
                });
            }
        });
    }
</script>
</body>
</html>
